package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.Local;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.EGravDaoInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.EGravTBL;

/**
 * Session Bean implementation class EGravDao
 * @author Patrick kendzo
 * Email: pkendzo@msn.com
 */

@Stateless
@Local( { EGravDaoInt.class })
public class EGravDao implements EGravDaoInt
{

	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager	em	= null;

	/**
	 * Default constructor.
	 */
	public EGravDao()
	{
		
	}

	@Override
	public void delete(Long todo)
	{
		EGravTBL item = em.find(EGravTBL.class, todo);

		CustomerTBL cust = item.getCustomer();

		cust.getEgravEintraege().remove(item);

		em.remove(item);
		em.flush();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EGravTBL> getEgravItemBYINTERVAL(String fromDatum,
			String toDatum)
	{
		try
		{
			return (List<EGravTBL>) em.createQuery(
					"SELECT e FROM EGravTBL e where  STR_TO_DATE(e.datum,'%d.%m.%Y') between "
					+"STR_TO_DATE('"+fromDatum+"','%d.%m.%Y') and  STR_TO_DATE('"+toDatum+"','%d.%m.%Y') order by e.datum").getResultList();
		}
		catch (Exception e)
		{
			throw new RuntimeException(
					"Could not retrieve Egrav items for this Interval", e);
		}
	}

	@Override
	public void persist(EGravTBL todo)
	{
		em.persist(todo);
		em.flush();

	}

	@Override
	public EGravTBL retrieveEgravItemByID(Long id)
	{
		return em.find(EGravTBL.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EGravTBL> retrieveEgravItemsByCustomer(String matricule)
	{
		try {
            return (List<EGravTBL>) em.createQuery(
                    "select e from EGravTBL e where e.customer = '" + matricule + "' order by e.datum").getResultList();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Could not retrieve Egrav item for this Customer", e);
        }
	}

	@Override
	public void update(EGravTBL todo)
	{
		em.merge(todo);
        em.flush();


	}

}
